package cn.yitun.chat.yitunservermanagecore.general.manage.personal.service.impl;

import cn.yitun.chat.yituncommonmessage.result.ResultMessage;
import cn.yitun.chat.yituncommonutil.YitunMD5Util;
import cn.yitun.chat.yituncommonutil.YitunStringUtil;
import cn.yitun.chat.yitunservercommonlib.converter.dto2po.user.UserDto2PoConverter;
import cn.yitun.chat.yitunservercommonlib.dataentity.po.system.user.UserInfo;
import cn.yitun.chat.yitunservercommonlib.dataentity.vo.system.user.UserVo;
import cn.yitun.chat.yitunservercommonlib.util.PinYinUtil;
import cn.yitun.chat.yitunservercommonlib.util.codec.IdGen;
import cn.yitun.chat.yitunserverimbase.dao.system.UserDao;
import cn.yitun.chat.yitunservermanagecore.general.manage.personal.service.PersonalService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * date 2018-06-13 10:27:23<br>
 * description
 * 
 * @author yitun<br>
 * @since
 */
@Service
public class PersonalServiceImpl implements PersonalService {

	@Resource
	private UserDao userDAO;

	public UserInfo getUser(Long id) {
		id = null==id ? 0l : id;
		UserInfo user = userDAO.get(id);
		return user;
	}


	public UserVo getUserVo(Long currentUserId) {
		return userDAO.getVO(currentUserId);
	}

	public ResultMessage updatePassword(Long id, String newPassword, String oldPassword) {
		ResultMessage rm = new ResultMessage();
		try {
			if (null != id && YitunStringUtil.isNotEmpty(newPassword)) {
				UserInfo user = userDAO.get(id);
				if (null != user) {
					if (user.getPassword().equals(oldPassword)) {
						userDAO.updatePassword(id, newPassword);
					} else {
						rm.addWarning("003", "原密码错误！");
					}
				} else {
					rm.addWarning("002", "修改失败！");
				}
			} else {
				rm.addWarning("001", "修改失败！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			rm.addError("500", "系统异常");
		}
		return rm;
	}

	/**
	 * 初始化用户数据，
	 */
    public void formatAllUserMag() {
		List<UserInfo> userList = userDAO.list(null);
		userList
				.stream()
				.filter(user -> user.getId() != 1)
				.forEach(user -> {
					user.setPassword(YitunMD5Util.md5L32("123456"));
					if (YitunStringUtil.isNotEmpty(user.getNickname()))
						user.setNickname(user.getName());
					user.setSpell(PinYinUtil.getFullSpell(user.getName()));
					user.setSimpleSpell(PinYinUtil.getFirstSpell(user.getName()));
					user.setPrivateKey(IdGen.uuid());
					user.setCode(IdGen.uuid());
					userDAO.updatePersonal(UserDto2PoConverter.INSTANCE.do2dto(user));
				});
    }
}
